package com.caigou.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.caigou.bean.cms.entity.Channel;
import com.caigou.bean.param.SubstationBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class HtmlBuildSubstationComponent {

    @Value("${yzb.domain}")
    private String yzbDomain;
    @Value("${yzb.request-url}")
    private String yzbRequestUrl;

    @Resource
    private TemplateComponent templateComponent;

    public void buildSubstation(Channel channel, String regionCode, String regionName, Integer regionLevel, String templateCode){
        // 封装模板参数
        Map<String, Object> map = new HashMap<>();
        map.put("yzbDomain",yzbDomain);
        map.put("channel", channel);
        map.put("regionCode", regionCode);
        map.put("regionName", regionName);
        try {
            // 网络请求类
            CloseableHttpClient httpClient = SSLClientComponent.createHttpClient();
            HttpPost httpPost;
            HttpResponse httpResponse;
            HttpEntity entity;
            // 公共请求参数
            URIBuilder builder = new URIBuilder(yzbRequestUrl);
            httpPost = new HttpPost(builder.build());// post请求方式
            //准备json数据发送参数
            JSONObject paramIn = new JSONObject();
            paramIn.put("pageSize", channel.getChannelCount());
            paramIn.put("queryText", "");
            //构造内层json对象
            JSONArray param = new JSONArray();
            JSONObject list = new JSONObject();
            list.put("regionCode", regionCode);
            list.put("regionName", regionName);
            list.put("regionLevel", regionLevel);
            param.add(list);
            paramIn.put("regionList", param);
            //处理中文乱码问题
            StringEntity stringEntity = new StringEntity(paramIn.toString(),"utf-8");
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            //发送请求
            httpResponse = httpClient.execute(httpPost);
            entity = httpResponse.getEntity();
            JSONObject responseJSON = JSONObject.parseObject(EntityUtils.toString(entity));
            if (responseJSON.getString("status").equals("200")){
                // 接口请求成功--获取data中的数据
                String data = responseJSON.getString("data");
                if (null != data && !data.equals("")){
                    // 数据中有内容
                    JSONObject dataJSON = JSONObject.parseObject(data);
                    String content = dataJSON.getString("content");
                    if (null != content && !content.equals("")){
                        // 能够获取到数据
                        List<SubstationBean> substationBean = JSON.parseArray(content, SubstationBean.class);
                        substationBean.forEach(item -> item.setUrl(yzbDomain+"/detail/"+item.getId()));
                        map.put("list", substationBean);
                        templateComponent.createHtml(templateCode, map);
                    } else {
                        log.error("未获取到数据，content为空 param={}",paramIn);
                    }
                } else {
                    log.error("未获取到数据，data为空 param={}",paramIn);
                }
            } else {
                log.error("接口请求不通，接口状态不为200 param={}",paramIn);
            }
        } catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

//    public static void main(String[] args) {
//        // 网络请求类
//        try {
//            CloseableHttpClient httpClient = SSLClientComponent.createHttpClient();
//            HttpPost httpPost;
//            HttpResponse httpResponse;
//            HttpEntity entity;
//            // 公共请求参数
//            URIBuilder builder = new URIBuilder("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxeebdfaa8967f51e1&secret=7af1b695d8ffacdb320e7137c6773b3f");
////            URIBuilder builder = new URIBuilder("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx20c094354adc43d6&secret=14ce3bf116a1866e905d61ece6306bca");
//            httpPost = new HttpPost(builder.build());// post请求方式
//            //处理中文乱码问题
//            JSONObject paramIn = new JSONObject();
//            StringEntity stringEntity = new StringEntity(paramIn.toString(),"utf-8");
//            stringEntity.setContentEncoding("UTF-8");
//            stringEntity.setContentType("json");
//            httpPost.setEntity(stringEntity);
//            //发送请求
//            httpResponse = httpClient.execute(httpPost);
//            entity = httpResponse.getEntity();
//            JSONObject responseJSON = JSONObject.parseObject(EntityUtils.toString(entity));
//            String accessToken= (String) responseJSON.get("access_token");
//            if (null != accessToken && !("").equals(accessToken)){
//                log.info("token请求成功 accessToken={}", accessToken);
//
//            }
//        } catch (Exception e) {
//            log.error(e.getMessage());
//        }
//    }


}
